<template>
  <view class="store">
    <view class="card-box">
      <view class="form-item">
        <view class="form-item-key">
          <text class="rules">*</text>
          联系人
        </view>
        <up-input
          placeholder="请填写姓名，10个字以内"
          maxlength="10"
          border="none"
          v-model="form.name"
          inputAlign="right"
        ></up-input>
      </view>
      <view class="form-item">
        <view class="form-item-key">
          <text class="rules">*</text>
          联系电话
        </view>
        <up-input
          placeholder="请填写"
          maxlength="20"
          border="none"
          v-model="form.phone"
          inputAlign="right"
        ></up-input>
      </view>
      <view class="form-item">
        <view class="form-item-key">
          <text class="rules">*</text>
          所在地区
        </view>

        <view class="city-select-btn" @click="onOpenPopup">
          <view v-if="form.province && form.city && form.district">
            <text v-for="(city, index) in selectCity" :key="city.id">
              {{ city.name }}{{ index < selectCity.length - 1 ? "/" : "" }}
            </text>
          </view>
          <view v-else>请选择</view>
        </view>
      </view>

      <view class="store-location">
        <view class="location-top">
          <view>
            <text class="rules">*</text>
            门店地址
          </view>
          <view class="location-btn" @click="chooseAddressView">选择定位</view>
        </view>
        <view>
          <up-textarea v-model="form.address"></up-textarea>
        </view>
      </view>
    </view>

    <view v-if="props.type == 'add'" class="card-box">
      <view class="p-20">
        <u-checkbox-group>
          <u-checkbox
            :checked="form.is_default"
            shape="circle"
            label="设为默认地址"
            @change="form.is_default = $event"
          ></u-checkbox>
        </u-checkbox-group>
      </view>
    </view>

    <view class="submit-box">
      <up-button
        type="primary"
        shape="circle"
        text="确认提交"
        @click="onSubmit"
      ></up-button>
    </view>

    <up-popup :show="popupShow" mode="bottom" round="10">
      <view class="popup-mian">
        <view class="popup-top">
          <view class="popup-btn cancel-btn" @click="onClosePopup">取消</view>
          <view class="popup-title">选择所在地区</view>
          <view class="popup-btn confirm-btn" @click="onConfirmPopup">
            确认
          </view>
        </view>
        <view class="city-select">
          <view
            class="select-item"
            v-for="(row, index) in selectCity"
            :key="index"
            :class="{ active: cityActive == index }"
            @click="onCityLevel(index)"
          >
            {{ row.name }}
          </view>
        </view>
        <scroll-view scroll-y style="height: 500rpx">
          <view class="city-list">
            <view
              class="city-item flex justify-between"
              :class="{ active: item.id == selectCity[cityActive].id }"
              v-for="item in cityList"
              :key="item.id"
              @click="onCitySelect(item)"
            >
              <text>{{ item.name }}</text>
              <u-icon
                v-if="item.id == selectCity[cityActive].id"
                name="checkbox-mark"
                color="primary"
              ></u-icon>
            </view>
          </view>
        </scroll-view>
      </view>
    </up-popup>
  </view>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import { apiConfigAddress } from "@/common/apis/common.js";
import { useStore } from "vuex";

const store = useStore();

const props = defineProps({
  type: String,
  id: String,
});

const cityList = ref([]);

const selectCity = reactive([
  { id: 0, name: "选择省" },
  { id: 0, name: "选择市" },
  { id: 0, name: "选择区" },
]);

const popupShow = ref(false);

const cityActive = ref(0);

const form = reactive({
  province: 0,
  city: 0,
  district: 0,
  address: "",
  name: "",
  phone: "",
  longitude: "",
  latitude: "",
  is_default: false,
});

async function getConfigAddressData(parent_id) {
  const response = await apiConfigAddress({ parent_id });
  if (response) {
    cityList.value = response;
  }
}

function onOpenPopup() {
  popupShow.value = true;
}

function onCityLevel(index) {
  if (index == 0) {
    cityActive.value = 0;
    selectCity[1] = { id: "", name: "选择市" };
    selectCity[2] = { id: "", name: "选择区" };
    getConfigAddressData();
  } else if (index == 1 && selectCity[index].id) {
    cityActive.value = 1;
    selectCity[2] = { id: "", name: "选择区" };
    getConfigAddressData(selectCity[0].id);
  }
}

function onCitySelect(row) {
  selectCity[cityActive.value] = JSON.parse(JSON.stringify(row));
  if (cityActive.value < 2) {
    cityActive.value++;
    getConfigAddressData(row.id);
  }
}

function onClosePopup() {
  popupShow.value = false;
}

function onConfirmPopup() {
  form.province = selectCity[0].id || 0;
  form.city = selectCity[1].id || 0;
  form.district = selectCity[2].id || 0;
  if (!form.province) {
    return uni.showToast({
      title: "请选择省份",
      icon: "none",
    });
  } else if (!form.city) {
    return uni.showToast({
      title: "请选择市",
      icon: "none",
    });
  } else if (!form.district) {
    return uni.showToast({
      title: "请选择区",
      icon: "none",
    });
  }
  popupShow.value = false;
}

//选择地址
function chooseAddressView() {
  uni.chooseLocation({
    success: (res) => {
      if (!res.name || !res.address || !res.latitude || !res.longitude) return;
      form.latitude = String(res.latitude);
      form.longitude = String(res.longitude);
      form.address = res.address + res.name;
    },
  });
}

let isSubmit = false;

async function onSubmit() {
  if (!form.name) {
    return uni.showToast({
      title: "请输入联系人",
      icon: "none",
    });
  }
  if (!form.phone) {
    return uni.showToast({
      title: "请输入联系电话",
      icon: "none",
    });
  }
  if (!form.province && !form.city && !form.district) {
    return uni.showToast({
      title: "请选择所在地区",
      icon: "none",
    });
  }
  if (!form.address) {
    return uni.showToast({
      title: "请选择门店地址",
      icon: "none",
    });
  }
  if (isSubmit) return;
  isSubmit = true;
  uni.showLoading({ title: "提交中" });
  let respone = null;
  if (props.type == "add") {
    respone = await store.dispatch("fetchAddDeliver", form);
  } else if (props.type == "edit") {
    respone = await store.dispatch("fetchEditDeliver", form);
  }
  if (respone) {
    uni.showToast({
      title: "提交成功",
      icon: "success",
    });
    uni.navigateBack();
  }
  isSubmit = false;
  uni.hideLoading();
}

async function initFormData() {
  const response = await store.dispatch("fetchDeliverDetail", props.id);
  form.address = response.address;
  form.name = response.name;
  form.phone = response.phone;
  form.province = response.province.id;
  form.city = response.city.id;
  form.district = response.district.id;
  form.is_default = response.is_default;
  form.longitude = response.longitude;
  form.latitude = response.latitude;
  form.id = response.id;
  selectCity[0] = response.province;
  selectCity[1] = response.city;
  selectCity[2] = response.district;
}

onMounted(() => {
  cityActive.value = 0;
  selectCity[1] = { id: "", name: "选择市" };
  selectCity[2] = { id: "", name: "选择区" };
  getConfigAddressData();
  if (props.type == "edit") {
    initFormData();
  }
});
</script>

<style lang="scss" scoped>
.store {
  .card-box {
    margin: 20rpx;
    padding: 0 20rpx;
    border-radius: 20rpx;
    background-color: #ffffff;

    .form-item {
      height: 100rpx;
      display: flex;
      align-items: center;
      justify-content: space-between;
      border-bottom: 2rpx solid #f0f0f0;

      &:last-child {
        border-bottom: none;
      }

      .form-item-key {
        width: 160rpx;
      }

      .city-select-btn {
        flex: 1;
        padding: 10rpx 0;
        text-align: right;
      }
    }

    .store-location {
      padding-bottom: 20rpx;

      .location-top {
        height: 100rpx;
        display: flex;
        align-items: center;
        justify-content: space-between;

        .location-btn {
          color: #3cb9ef;
        }
        .location-address {
          width: 500rpx;
          text-align: right;
        }
      }

      .location-address {
        color: #333333;
        margin-top: 10rpx;
      }
    }

    .store-image {
      margin-bottom: 20rpx;

      .store-image-left {
        height: 80rpx;
        line-height: 80rpx;
      }
    }
  }

  .map-marker {
    height: 62rpx;
    position: absolute;
    top: 40%;
    left: 50%;
    transform: translate(-50%, -50%);
  }

  .submit-box {
    margin: 40rpx 20rpx 0;
  }

  .popup-mian {
    .popup-top {
      padding: 20rpx;
      background-color: #ffffff;
      display: flex;
      align-items: center;
      justify-content: space-between;

      .popup-title {
        font-size: 30rpx;
        font-weight: bold;
      }

      .cancel-btn {
        color: #666666;
      }

      .confirm-btn {
        color: #3cb9ef;
      }
    }

    .city-select {
      display: flex;
      align-items: center;
      justify-content: space-between;
      border-bottom: 2rpx solid #f0f0f0;

      .select-item {
        width: calc(100% / 3);
        padding: 20rpx;

        &.active {
          color: #3cb9ef;
        }
      }
    }

    .city-list {
      height: 500rpx;

      .city-item {
        height: 80rpx;
        border-bottom: 2rpx solid #f0f0f0;
        padding: 0 20rpx;
        line-height: 80rpx;
        &.active {
          color: $u-primary;
        }
      }
    }
  }

  .rules {
    color: #ff0000;
  }
}
</style>
